//
//  AppDelegate.m
//  TTLestening
//
//  Created by dllo on 16/3/21.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "AppDelegate.h"
#import <RESideMenu.h>
#import "XCLeftSetingController.h"
#import "XCFirstViewController.h"
#import "XTCellOfbofang.h"
#import "CircularProgressView.h"
#import "XCAVMusicPlayer.h"
#import "XTVCOfplayview.h"
#import "XCMVController.h"
#import "XCModelForEveryone.h"
#import <SDWebImage/UIImageView+WebCache.h>

#import "XTCellOftabgedan.h"


#import "ZFHttpManager.h"
#import "ZFDownloadViewController.h"
//#import "XTVCOfplayview.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <AVOSCloud.h>
// 腾讯开放平台(QQ)
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

// 微信
#import "WXApi.h"

// 新浪微博
#import "WeiboSDK.h"


#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface AppDelegate ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>



@property (nonatomic,retain)UIButton *play;

@property (nonatomic,retain)UIButton *songlist;

@property (nonatomic,retain)UIView *buttonview;

@property (nonatomic,retain)UICollectionView *collection;

@property (nonatomic,retain)UICollectionViewFlowLayout *flowlayout;

@property (nonatomic, assign) NSInteger index;
@property (nonatomic,strong)NSString *duar;

@property (nonatomic,strong)NSString *curr;

@property (nonatomic,strong)NSString *progress;
@property (nonatomic, strong)NSMutableArray *array;
//偏移量个数
@property (nonatomic,assign)NSInteger number;
//@property (nonatomic, strong)XTVCOfplayview *playDetailView;


@property (nonatomic,strong)UIView *viewbacklist;


@property (nonatomic,assign)BOOL complete;


@property (nonatomic,retain)UITableView *tableview;


@property (nonatomic,assign)NSInteger index2;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    

    
    self.complete = YES;
      


    // 监听网络
    [[ZFHttpManager shared] registerNetworkStatusMoniterEvent];
    

    [AVOSCloud setApplicationId:@"2TiJxv8AOstgiaUH3uQEPBTl-gzGzoHsz"
                      clientKey:@"U2j8TOVU6NA0KYAUonoIq6UU"];


    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    XCFirstViewController *mainVC = [[XCFirstViewController alloc] init];
    
    XCLeftSetingController *leftSeting = [[XCLeftSetingController alloc] init];
    self.navi = [[UINavigationController alloc] initWithRootViewController:mainVC];
    
    self.backview = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT - 49, WIDTH - 10, 49)];
    self.buttonview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH - 100, 0, 100, 49)];
    [self.backview addSubview:self.buttonview];
    self.buttonview.backgroundColor = [UIColor yellowColor];
    
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    self.play.frame = CGRectMake(0, 0, 25, 25);
    [self.buttonview addSubview:self.play];

    
    [self.play setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    self.play.center = CGPointMake(30, 25);
    [self.play addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.songlist = [UIButton buttonWithType:UIButtonTypeCustom];
    self.songlist.frame = CGRectMake(0, 0, 30, 30);
    [self.buttonview addSubview:self.songlist];
    [self.songlist setBackgroundImage:[UIImage imageNamed:@"iconfont-iconfontttpodicon3-4"] forState:UIControlStateNormal];
    self.songlist.center = CGPointMake(75, 25);
    
    [self.songlist addTarget:self action:@selector(songlist:) forControlEvents:UIControlEventTouchUpInside];
    self.flowlayout = [[UICollectionViewFlowLayout alloc]init];
    
    self.flowlayout.itemSize = CGSizeMake(WIDTH - 100,49);
    
    self.flowlayout.minimumInteritemSpacing = 0;
    
    self.flowlayout.minimumLineSpacing = 0;
    
    self.flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH - 100, 49) collectionViewLayout:self.flowlayout];
    
    self.collection.backgroundColor = [UIColor whiteColor];
    
    
    
    [self.backview addSubview:self.collection];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    self.collection.pagingEnabled = YES;
    self.collection.bounces = YES;
    
    self.collection.showsVerticalScrollIndicator = NO;
    
    
    [self.collection registerClass:[XTCellOfbofang class] forCellWithReuseIdentifier:@"pool1"];
    
    
    [self playHistory];
    
    
    [self.navi.view addSubview:self.backview];
    

   [[NSNotificationCenter defaultCenter] addObserverForName:@"giveValue" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
      
       self.index = [[note.userInfo objectForKey:@"index"] integerValue];
       
      // NSLog(@"ddddddddddddd%ld",self.index);
       
       self.array = [note.userInfo objectForKey:@"modelArray"];
       
     
       self.collection.contentOffset = CGPointMake(self.index * (WIDTH - 100), 0);
        [self.collection reloadData];
       
       
   }];


//    [[NSNotificationCenter defaultCenter] addObserverForName:@"giveValue" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
//        
//        self.index = [[note.userInfo objectForKey:@"index"] integerValue];
//        
//        // NSLog(@"ddddddddddddd%ld",self.index);
//        
//        self.array = [note.userInfo objectForKey:@"modelArray"];
//        
//        
//        self.collection.contentOffset = CGPointMake( self.index * (WIDTH - 100), 0);
//        [self.collection reloadData];
//    }];
    

    
    
    

    
    RESideMenu *leftVC = [[RESideMenu alloc] initWithContentViewController:self.navi leftMenuViewController:leftSeting rightMenuViewController:nil];
    
    [self.window bringSubviewToFront:self.backview];
    
    self.window.rootViewController = leftVC;
    
    [self.window makeKeyAndVisible];
    

    [self creatKVOAction];
    
//           return YES;
    
   
  

    
#pragma mark Share注册------------------------------
    
    [ShareSDK registerApp:@"11568dc80f1b4"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ)] onImport:^(SSDKPlatformType platformType) {
                                
                                switch (platformType) {
                                        
                                    case SSDKPlatformTypeSinaWeibo:
                                        [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                                        
                                        break;
                                        
                                    case SSDKPlatformTypeWechat:
                                        [ShareSDKConnector connectWeChat:[WXApi class]];
                                        break;
                                        
                                    case SSDKPlatformTypeQQ:
                                        [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                                        
                                        break;
                                        
                                    default:
                                        
                                        break;
                                }
                                
                            } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                                //
                                switch (platformType)
                                {
                                    case SSDKPlatformTypeSinaWeibo:
                                        
                                        //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                                        [appInfo SSDKSetupSinaWeiboByAppKey:@"568898243"
                                                                  appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
                                                                redirectUri:@"天天动听"
                                                                   authType:SSDKAuthTypeBoth];
                                        
                                        break;
                                        
                                    case SSDKPlatformTypeWechat:
                                        
                                        [appInfo SSDKSetupWeChatByAppId:@"wx8ab17600e33f419e"appSecret:@"1573555b341eb0dea907eac00a6e8b5a"];
                                        
                                        break;
                                        
                                    case SSDKPlatformTypeQQ:
                                        
                                        [appInfo SSDKSetupQQByAppId:@"1105317480"
                                                             appKey:@"TNdehkRaCsmVIZ6V"
                                                           authType:SSDKAuthTypeBoth];
                                        
                                        break;
                                        
                                    default:
                                        break;
                                }
                                
                            }];
    
    
    
    return YES;


}

-(void)creatKVOAction{
    [self.collection addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:@"ddd"];

}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    CGFloat x = [[change objectForKey:@"new"]CGPointValue].x;
    
    
    
    self.index2 = x / (WIDTH - 100);
    
    
    NSLog(@"qweqweeeeeee%ld",self.index2);
    
    [self.tableview reloadData];
    
}






- (void)playHistory {

    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"history.plist"];
    NSLog(@"%@", file);
    
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:file];

    self.array = [NSMutableArray array];
    
    XCModelForEveryone *model = [[XCModelForEveryone alloc] init];
    [model setValuesForKeysWithDictionary:dic];
    
    [self.array addObject:model];
    [self.collection reloadData];

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    

  

    //NSLog(@"   %@", self.array);

    return self.array.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    XTCellOfbofang *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];


    cell.backgroundColor = [UIColor colorWithRed:0.275 green:0.796 blue:0.729 alpha:1.000];

    

    
    cell.cirview.playOrPauseButtonIsPlaying  = YES;
    
    XCModelForEveryone *model = [self.array objectAtIndex:indexPath.row];
    
    [cell passModelForSong:model];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"1314" object:nil userInfo:@{@"music":self.array , @"index":[NSString stringWithFormat:@"%ld",indexPath.row]}];
    
    [[NSNotificationCenter defaultCenter]addObserverForName:@"qiushuju" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"1315" object:nil userInfo:@{@"music":self.array , @"index":[NSString stringWithFormat:@"%ld",indexPath.row]}];
    }];
    
    
//    NSLog(@"%@",self.array);
    
    NSLog(@"%ld",indexPath.row);
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"pushprogress" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        self.duar = [note.userInfo objectForKey:@"duration"];
        
        self.curr = [note.userInfo objectForKey:@"current"];
        
        self.progress = [note.userInfo objectForKey:@"progress"];
    
        float floatString = [self.progress floatValue];
        
        cell.cirview.progress = floatString;
        
        //XTVCOfplayview *playView = [[XTVCOfplayview alloc] init];
        // [self.playDetailView passCurrentTime:self.curr totalTime:self.duar];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"currenTime" object:nil userInfo:@{@"current": self.curr, @"total": self.duar}];
        
        [cell.cirview setNeedsDisplay];
        
    }];
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    XTVCOfplayview *vc = [[XTVCOfplayview alloc]init];
    
//    [self.navi presentViewController:vc animated:YES completion:^{
//        
//        
//        //     XTVCOfplayview *playView = [[XTVCOfplayview alloc] init];
//        //     [playView passCurrentTime:self.curr totalTime:self.duar songArray:self.array index:self.index];
//        
//        
//    }];

    [self.navi presentViewController:vc animated:YES completion:^{
     
     
     [[NSNotificationCenter defaultCenter] postNotificationName:@"postPlayView" object:nil userInfo:@{@"array":self.array, @"index":[NSString stringWithFormat:@"%ld", self.index]}];

     
     
 }];
    
    NSLog(@"进入播放页面");
}

-(void)play:(UIButton *)buuton{
    
    if (buuton.selected) {
        
        NSLog(@"播放");
        [self.play setBackgroundImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
        
        
    }else {
        
        NSLog(@"暂停");
        [self.play setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-4"] forState:UIControlStateNormal];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pause" object:nil];
        
    }
    
    buuton.selected = !buuton.selected;
    
}

-(void)songlist:(UIButton *)button{
    
    NSLog(@"出现歌单页面");


        if (self.complete == YES) {
        self.viewbacklist = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, (HEIGHT - 49))];
        
        self.viewbacklist.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        
        [self.navi.view addSubview:self.viewbacklist];
        
        [self.navi.view bringSubviewToFront:self.viewbacklist];
        
        self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0.4 * HEIGHT, WIDTH, 0.6* HEIGHT - 49) style:UITableViewStylePlain];
        
        self.tableview.backgroundColor = [[UIColor colorWithRed:0.208 green:0.627 blue:0.980 alpha:1.000]colorWithAlphaComponent:1];
        
        self.tableview.delegate = self;
        self.tableview.dataSource = self;
            self.tableview.bounces = NO;
            
        self.tableview.separatorStyle = 1;
        
//        [self.tableview selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index2 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
   
            
//            [self.tableview reloadData];
           
         UINib *nib = [UINib nibWithNibName:@"XTCellOftabgedan" bundle:[NSBundle mainBundle]];
            
         [self.tableview registerNib:nib forCellReuseIdentifier:@"pool1"];
            
            
        [self.viewbacklist addSubview:self.tableview];
        
        self.complete = NO;
        
        }else{
            
        self.viewbacklist.alpha = 0;
          
        [self.viewbacklist removeFromSuperview];
            
            
        self.complete = YES;
        }
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 50;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    XTCellOftabgedan *cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
    NSString *str = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    
    cell.songnumber.text = str;
    
    
    cell.selectionStyle = 0;
    
    XCModelForEveryone *model = [self.array objectAtIndex:indexPath.row];
    
    NSString *songname = model.name;
    
    NSString *songer = model.singerName;
    
    NSString *str2 = [NSString stringWithFormat:@"%@ - %@",songname,songer];
    
    
    cell.songname.text = str2;
    
    
    if (self.index2 == indexPath.row) {
        cell.image.hidden = NO;
        
    }else{
        cell.image.hidden = YES;
    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
   NSString *key = @"歌曲列表";
    
    
    
    return key;
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [[NSNotificationCenter defaultCenter] postNotificationName:@"1314" object:nil userInfo:@{@"music":self.array , @"index":[NSString stringWithFormat:@"%ld",indexPath.row]}];
  
    self.collection.contentOffset = CGPointMake(indexPath.row * (WIDTH - 100), 0);
    
   

//    ZFDownloadViewController *down = [[ZFDownloadViewController alloc] init];
//    [self.navi pushViewController:down animated:NO];



}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
